package cn.hznc.controller.service.retrospect;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.request.retrospect.ToolRestrospectReq;
import cn.hznc.domain.request.retrospect.ToolRetrospectIndexReq;
import cn.hznc.domain.response.PageResult;
import cn.hznc.exception.ToolLifeCycleEx;
import cn.hznc.exception.ToolLifeCycleException;
import cn.hznc.mapper.ToolForkInfoMapper;
import cn.hznc.mapper.ToolPartMapper;
import cn.hznc.repository.AssemblyToolInventoryRepository;
import cn.hznc.repository.InventoryLocationRespository;
import cn.hznc.repository.ToolPartRespository;
import cn.hznc.repository.TypeItemRepository;
import cn.hznc.utils.CommonUtil;
import cn.hznc.vo.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author：Administrator6
 * @Date：2023/4/12 11:32
 */
@Service
public class ToolRetrospectService {

    @Resource
    private ToolPartRespository toolPartRespository;

    @Resource
    private ToolPartMapper toolPartMapper;

    @Resource
    private ToolForkInfoMapper toolForkInfoMapper;

    @Resource
    private InventoryLocationRespository inventoryLocationRespository;

    @Resource
    private AssemblyToolInventoryRepository assemblyToolInventoryRepository;

    @Resource
    private TypeItemRepository typeItemRepository;

    @Resource
    private MinioProp minioProp;

    private static final List<String> toolTypeFilter = new ArrayList();
    private static final List<String> assemblyToolTypeFilter = new ArrayList();

    static {
        toolTypeFilter.add("A");
        toolTypeFilter.add("A001");
        toolTypeFilter.add("A002");
        assemblyToolTypeFilter.add("B");
        assemblyToolTypeFilter.add("A004");
        assemblyToolTypeFilter.add("A005");
    }

    public Object getToolRetrospectAllList(ToolRestrospectReq toolRestrospectReq) {
        PageHelper.startPage(toolRestrospectReq.getPageNum(), toolRestrospectReq.getPageSize());
        if(StringUtil.isNotEmpty(toolRestrospectReq.getWarehouseType())){
            List<Integer> locationIds = inventoryLocationRespository.selectLocationIdsByWarehouseType(toolRestrospectReq.getWarehouseType());
            toolRestrospectReq.setLocationIds(locationIds);
        }
        //条件查询工件列表
        List<ToolRestrospectVo> resultList = toolPartRespository.queryToolRetrospectAllList(toolRestrospectReq);
        PageInfo<ToolRestrospectVo> pageInfo = new PageInfo<>(resultList);
        //设置库位名称
        if(CollectionUtil.isNotEmpty(pageInfo.getList())){
            pageInfo.getList().forEach(toolRestrospectVo -> {
                LocationNameVo location = inventoryLocationRespository.queryLocation(toolRestrospectVo.getId());
                buildLocationName(toolRestrospectVo, location);
            });
        }
        return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
    }

    private void buildLocationName(ToolRestrospectVo toolRestrospectVo, LocationNameVo location) {
        StringBuilder stringBuilder = new StringBuilder();
        String locationName = stringBuilder.append(location.getTypeName()).append("-")
                .append(location.getWarehouseName()).append("-库位")
                .append(location.getLocationNum()).toString();
        toolRestrospectVo.setLocation(locationName);
    }

    public Object qryConditionType(String filter) {
        List<String> typeList = new ArrayList<>();
        if (toolTypeFilter.contains(filter)) {
            typeList = typeItemRepository.selectAllTypeName();
        } else if (assemblyToolTypeFilter.contains(filter)) {
            typeList = assemblyToolInventoryRepository.qryAllTypeName();
        }
        return typeList.stream().filter(s -> ObjectUtil.isNotNull(s) && StringUtil.isNotEmpty(s));
    }

    public Object getToolRetrospectIndex(ToolRetrospectIndexReq toolRetrospectIndexReq) {
        List<Integer> locationIds = new ArrayList<>();
        if(StringUtil.isNotEmpty(toolRetrospectIndexReq.getWarehouseType())
                || ObjectUtil.isNotNull(toolRetrospectIndexReq.getWarehouseId())
                || ObjectUtil.isNotNull(toolRetrospectIndexReq.getLocationId())){
            locationIds = inventoryLocationRespository.selectLocationId(toolRetrospectIndexReq);
        }
//        if(ObjectUtil.isNotNull(toolRetrospectIndexReq.getWarehouseType())){
//            ids =
//            if (ObjectUtil.isNotNull(toolRetrospectIndexReq.getWarehouseId())) {
//                //根据库位过滤
//                ids = inventoryLocationRespository.selectLocationId(toolRetrospectIndexReq.getWarehouseId()).stream().map(InventoryLocationEntity::getId).collect(Collectors.toList());
//                if (ObjectUtil.isNotNull(toolRetrospectIndexReq.getLocationId())) {
//                     ids = ids.stream().filter(integer -> integer.equals(toolRetrospectIndexReq.getLocationId())).collect(Collectors.toList());
//                }
//            }
//        }
        List<ToolPartEntity> resultList;
        resultList = toolPartRespository.selectToolRetrospectIndex(toolRetrospectIndexReq.getUniqueId(), toolRetrospectIndexReq.getPartno(), toolRetrospectIndexReq.getToolNo(), locationIds , toolRetrospectIndexReq.getSortFlag() , toolRetrospectIndexReq.getTypeFlag());
        if (CollectionUtil.isNotEmpty(resultList) && assemblyToolTypeFilter.contains(toolRetrospectIndexReq.getType()) && StringUtil.isNotEmpty(toolRetrospectIndexReq.getTypeName())) {
            //根据总成类型过滤
            List<String> toolNoList = assemblyToolInventoryRepository.selectToolNoByType(toolRetrospectIndexReq.getTypeName());
            resultList = resultList.stream()
                    .filter(toolPartEntity -> StringUtil.isNotEmpty(toolPartEntity.getToolNo()))
                    .filter(toolPartEntity -> toolNoList.contains(toolPartEntity.getToolNo())).collect(Collectors.toList());
        } else if (CollectionUtil.isNotEmpty(resultList) && toolTypeFilter.contains(toolRetrospectIndexReq.getType()) && StringUtil.isNotEmpty(toolRetrospectIndexReq.getTypeName())){
            //根据零件类型过滤
            String type = typeItemRepository.selectTypeByTypeName(toolRetrospectIndexReq.getTypeName());
            resultList = resultList
                    .stream()
                    .filter(toolPartEntity -> StringUtil.isNotEmpty(toolPartEntity.getToolType()))
                    .filter(toolPartEntity -> toolPartEntity.getToolType().length() >= type.length() && toolPartEntity.getToolType().contains(type))
                    .collect(Collectors.toList());
        }
        List<ToolPartEntity> retList = new ArrayList<>();
        //分页
        if (!CollectionUtil.isEmpty(resultList)) {
            retList = CommonUtil.pageList(resultList, toolRetrospectIndexReq.getPageNum(), toolRetrospectIndexReq.getPageSize());
        }
        List<LocationNameVo> locationNameVos = new ArrayList<>();
        Map<Integer , LocationNameVo> groupByIdMap = new HashMap<>();
        List<Integer> inventoryLocationIds = retList
                .stream()
                .filter(toolPartEntity ->ObjectUtil.isNotNull(toolPartEntity.getInventoryLocationId()))
                .map(ToolPartEntity::getInventoryLocationId)
                .collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(retList) &&  CollectionUtil.isNotEmpty(inventoryLocationIds)){
            locationNameVos = inventoryLocationRespository.queryLocationByLocationId(inventoryLocationIds);
            groupByIdMap = locationNameVos.stream().collect(Collectors.toMap(LocationNameVo::getId , LocationIdVo->LocationIdVo));
        }
        //评价图片地址

        for (ToolPartEntity toolPartEntity : retList) {
            //LocationNameVo locationNameVo = inventoryLocationRespository.queryLocation(toolPartEntity.getId());
            LocationNameVo locationNameVo = groupByIdMap.get(toolPartEntity.getInventoryLocationId());
            if (ObjectUtil.isNotNull(locationNameVo) && ObjectUtil.isNotNull(locationNameVo.getId())) {
                StringBuilder stringBuilder = new StringBuilder();
                String locationName = stringBuilder.append(locationNameVo.getTypeName()).append("-").append(locationNameVo.getWarehouseName()).append("-库位").append(locationNameVo.getLocationNum()).append("-位置").append(locationNameVo.getRow()).append("-").append(locationNameVo.getColumn()).toString();
//                    toolInventoryVo.setWarehouseName(locationName);
                toolPartEntity.setWarehouseName(locationName);
            }
            if (StringUtil.isNotEmpty(toolPartEntity.getToolNo())) {
                String imageUrl = assemblyToolInventoryRepository.selectImageByToolNo(toolPartEntity.getToolNo());
                if (StringUtil.isNotEmpty(imageUrl)) {
                    toolPartEntity.setImage(minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + imageUrl);
                }
            }
            //toolPartEntity.setImage(minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + toolPartEntity.getImage());
        }
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("list", retList);
        retMap.put("total", resultList.size());
        return retMap;
    }

    public Map<String, Object> toolRetrospectRecord(String uniqueId) {
        ToolPartEntity toolPartEntity = getToolPartEntity(uniqueId);
        Map<String, Object> recordMap = new HashMap<>();
        //报废记录
        String damageLog = toolPartEntity.getDamageLog();
        List<AssemblyDamageLogVo> assemblyDamageLogVo = JSONArray.parseArray(damageLog, AssemblyDamageLogVo.class);
        recordMap.put("damageLog", ObjectUtil.isNull(assemblyDamageLogVo) ? new ArrayList<>() : assemblyDamageLogVo);
        //组装拆分记录
        String log = toolPartEntity.getLog();
        List<AssembleLogVo> assembleLogVos = JSONArray.parseArray(log, AssembleLogVo.class);
        recordMap.put("assembleLog", ObjectUtil.isNull(assembleLogVos) ? new ArrayList<>() : assembleLogVos);
        //出入库记录
        //零件组装后总成的出入库记录
        List<Integer> ids = new ArrayList<>();
        ids.add(toolPartEntity.getId());
        //查看是否有历史组装记录
        String assemblyUniqueIdHistory = toolPartEntity.getAssemblyUniqueIdHistory();
        if (StringUtil.isNotEmpty(assemblyUniqueIdHistory)) {
            List<String> uniqueIds = JSONArray.parseArray(assemblyUniqueIdHistory, String.class);
            ids.addAll(uniqueIds.stream().map(s -> toolPartRespository.getIdByUniqueId(s)).collect(Collectors.toList()));
        }
        List<InOrOutboundRecordVo> inOrOutboundRecord = toolPartRespository.selectRecord(ids);
        recordMap.put("inOrOutBoundLog", inOrOutboundRecord);
        return recordMap;
    }

    private ToolPartEntity getToolPartEntity(String uniqueId) {
        LambdaQueryWrapper<ToolPartEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ToolPartEntity::getUniqueId, uniqueId);
        return toolPartMapper.selectOne(wrapper);
    }

    public Object getToolRetrospectDetail(String uniqueId) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        ToolPartEntity toolPartEntity = getToolPartEntity(uniqueId);
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = assemblyToolInventoryRepository.selectByToolNo(toolPartEntity.getToolNo());
        Map<String, Object> assemblyToolInfoMap = new HashMap<>();
        assemblyToolInfoMap.put("name", assemblyToolInventoryEntity.getName());
        assemblyToolInfoMap.put("toolType", assemblyToolInventoryEntity.getToolType());
        assemblyToolInfoMap.put("shankType", assemblyToolInventoryEntity.getShankType());
        if (StringUtil.isNotEmpty(toolPartEntity.getParams())) {
            JSONObject jsonObject = JSONObject.parseObject(toolPartEntity.getParams());
            List<String> toolTypes = (List<String>) jsonObject.get("toolType");
            List<String> shankTypes = (List<String>) jsonObject.get("shankType");
            assemblyToolInfoMap.put("toolUniqueIds", toolTypes);
            assemblyToolInfoMap.put("shankUniqueIds", shankTypes);
        }
        Map<String, Object> recordMap = toolRetrospectRecord(uniqueId);
        resultList.add(assemblyToolInfoMap);
        resultList.add(recordMap);
        return resultList;
    }

    public Object getToolPartRetrospectDetail(String uniqueId) throws ToolLifeCycleException {
        Map<String , Object> retMap = new HashMap<>();
        if(StringUtil.isEmpty(uniqueId)){
            throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_NO_EXIST.getCode() , ToolLifeCycleEx.TOOL_NO_EXIST.getMsg());
        }
        QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("unique_id" , uniqueId);
        ToolPartEntity toolPartEntity = toolPartMapper.selectOne(wrapper);
        ToolForkInfoEntity toolForkInfoEntity = new ToolForkInfoEntity();
        //类型基础信息
        retMap.put("toolForkInfo", toolForkInfoEntity);
        if(ObjectUtil.isNotNull(toolPartEntity)){
            LambdaQueryWrapper<ToolForkInfoEntity> toolForkInfoEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            toolForkInfoEntityLambdaQueryWrapper.eq(ToolForkInfoEntity::getPartno , toolPartEntity.getPartno());
            toolForkInfoEntity = toolForkInfoMapper.selectOne(toolForkInfoEntityLambdaQueryWrapper);
            //类型基础信息
            retMap.put("toolForkInfo", toolForkInfoEntity);
        }
        Map<String, Object> recordMap = toolRetrospectRecord(uniqueId);
        retMap.put("record" , recordMap);
        return retMap;
    }

}
